<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管理系统 - 添加/编辑图书</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Noto Sans SC', Arial, sans-serif;
            background: linear-gradient(135deg, #f6f9fc 0%, #eef2f7 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 2rem;
        }
        .container {
            background-color: white;
            padding: 2.5rem;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            width: 90%;
            max-width: 600px;
            position: relative;
            overflow: hidden;
        }
        .container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #2ecc71, #27ae60);
        }
        h2 {
            text-align: center;
            margin-bottom: 2rem;
            color: #2c3e50;
            font-size: 1.8rem;
            font-weight: 700;
        }
        .form-group {
            margin-bottom: 1.5rem;
            position: relative;
        }
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #34495e;
            font-weight: 500;
            font-size: 0.95rem;
        }
        .form-group input {
            width: 100%;
            padding: 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background-color: #f8f9fa;
        }
        .form-group input:focus {
            outline: none;
            border-color: #2ecc71;
            background-color: white;
            box-shadow: 0 0 0 3px rgba(46, 204, 113, 0.1);
        }
        .form-group input::placeholder {
            color: #95a5a6;
        }
        .form-group input[type="file"] {
            padding: 0.8rem;
            background-color: white;
            cursor: pointer;
        }
        .form-group input[type="file"]::-webkit-file-upload-button {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
            padding: 0.8rem 1.5rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            margin-right: 1rem;
            transition: all 0.3s ease;
        }
        .form-group input[type="file"]::-webkit-file-upload-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(46, 204, 113, 0.2);
        }
        .image-preview {
            margin-top: 1rem;
            max-width: 200px;
            border-radius: 8px;
            display: none;
        }
        .action-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 2rem;
            gap: 1rem;
        }
        .submit-btn, .back-btn {
            flex: 1;
            padding: 1rem;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .submit-btn {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
        }
        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(46, 204, 113, 0.2);
        }
        .submit-btn:active {
            transform: translateY(0);
        }
        .back-btn {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
        }
        .back-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.2);
        }
        .back-btn:active {
            transform: translateY(0);
        }
        .message {
            text-align: center;
            margin-bottom: 1.5rem;
            padding: 1rem;
            border-radius: 8px;
            font-size: 0.95rem;
            display: none;
        }
        .message.error {
            background-color: #ff6b6b;
            color: white;
            display: block;
        }
        .message.success {
            background-color: #2ecc71;
            color: white;
            display: block;
        }
        .loading {
            display: none;
            text-align: center;
            margin: 1rem 0;
        }
        .loading-spinner {
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #2ecc71;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        @media (max-width: 480px) {
            .container {
                padding: 2rem 1.5rem;
            }
            h2 {
                font-size: 1.5rem;
            }
            .action-buttons {
                flex-direction: column;
            }
            .submit-btn, .back-btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 id="formTitle">添加图书</h2>
        <div id="message" class="message"></div>
        <form id="bookForm" enctype="multipart/form-data">
            <input type="hidden" id="bookId">
            <div class="form-group">
                <label for="title">书名</label>
                <input type="text" id="title" required placeholder="请输入书名">
            </div>
            <div class="form-group">
                <label for="author">作者</label>
                <input type="text" id="author" required placeholder="请输入作者">
            </div>
            <div class="form-group">
                <label for="isbn">ISBN</label>
                <input type="text" id="isbn" required placeholder="请输入ISBN">
            </div>
            <div class="form-group">
                <label for="publisher">出版社</label>
                <input type="text" id="publisher" placeholder="请输入出版社">
            </div>
            <div class="form-group">
                <label for="publish_date">出版日期</label>
                <input type="date" id="publish_date">
            </div>
            <div class="form-group">
                <label for="category">分类</label>
                <input type="text" id="category" placeholder="请输入分类">
            </div>
            <div class="form-group">
                <label for="total_copies">总数量</label>
                <input type="number" id="total_copies" min="0" required placeholder="请输入总数量">
            </div>
            <div class="form-group">
                <label for="image">图书图片</label>
                <input type="file" id="image" accept="image/*">
                <img id="imagePreview" class="image-preview" alt="图书封面预览">
            </div>
            <div class="loading" id="loading">
                <div class="loading-spinner"></div>
            </div>
            <div class="action-buttons">
                <button type="submit" class="submit-btn">保存</button>
                <button type="button" class="back-btn" onclick="location.href='dashboard.html'">返回</button>
            </div>
        </form>
    </div>

    <script>
        // 显示消息
        function showMessage(message, type = 'error') {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = message;
            messageDiv.className = `message ${type}`;
            setTimeout(() => {
                messageDiv.style.display = 'none';
            }, 5000);
        }

        // 显示加载动画
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.querySelector('.submit-btn').disabled = true;
        }

        // 隐藏加载动画
        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
            document.querySelector('.submit-btn').disabled = false;
        }

        // 图片预览
        document.getElementById('image').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const preview = document.getElementById('imagePreview');
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                }
                reader.readAsDataURL(file);
            }
        });

        document.addEventListener('DOMContentLoaded', async () => {
            const urlParams = new URLSearchParams(window.location.search);
            const bookId = urlParams.get('id');
            const formTitle = document.getElementById('formTitle');
            const bookIdInput = document.getElementById('bookId');
            const titleInput = document.getElementById('title');
            const authorInput = document.getElementById('author');
            const isbnInput = document.getElementById('isbn');
            const publisherInput = document.getElementById('publisher');
            const publishDateInput = document.getElementById('publish_date');
            const categoryInput = document.getElementById('category');
            const totalCopiesInput = document.getElementById('total_copies');
            const imagePreview = document.getElementById('imagePreview');

            if (bookId) {
                formTitle.textContent = '编辑图书';
                bookIdInput.value = bookId;
                showLoading();
                try {
                    const response = await fetch(`../admin/book/${bookId}`);
                    if (response.ok) {
                        const book = await response.json();
                        titleInput.value = book.title;
                        authorInput.value = book.author;
                        isbnInput.value = book.isbn;
                        publisherInput.value = book.publisher || '';
                        publishDateInput.value = book.publish_date || '';
                        categoryInput.value = book.category || '';
                        totalCopiesInput.value = book.total_copies;
                        if (book.image_url) {
                            imagePreview.src = book.image_url;
                            imagePreview.style.display = 'block';
                        }
                    } else {
                        showMessage('获取图书信息失败');
                        setTimeout(() => {
                            location.href = 'dashboard.html';
                        }, 1500);
                    }
                } catch (error) {
                    console.error('Error fetching book:', error);
                    showMessage('获取图书信息失败');
                    setTimeout(() => {
                        location.href = 'dashboard.html';
                    }, 1500);
                } finally {
                    hideLoading();
                }
            } else {
                formTitle.textContent = '添加图书';
            }
        });

        document.getElementById('bookForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const bookId = document.getElementById('bookId').value;
            const title = document.getElementById('title').value;
            const author = document.getElementById('author').value;
            const isbn = document.getElementById('isbn').value;
            const publisher = document.getElementById('publisher').value;
            const publish_date = document.getElementById('publish_date').value;
            const category = document.getElementById('category').value;
            const total_copies = parseInt(document.getElementById('total_copies').value);
            const imageFile = document.getElementById('image').files[0];

            if (!title || !author || !isbn || !total_copies) {
                showMessage('请填写必填字段');
                return;
            }

            const formData = new FormData();
            formData.append('title', title);
            formData.append('author', author);
            formData.append('isbn', isbn);
            formData.append('publisher', publisher);
            formData.append('publish_date', publish_date);
            formData.append('category', category);
            formData.append('total_copies', total_copies);
            if (imageFile) {
                formData.append('image', imageFile);
            } else if (bookId) {
                // If it's an edit and no new image is selected, send a flag to keep existing image
                formData.append('keep_existing_image', 'true');
            }

            let url = '../admin/book';
            let method = 'POST';

            if (bookId) {
                url = `../admin/book/${bookId}`;
                method = 'PUT'; // Change to PUT for update
            }

            showLoading();

            try {
                const response = await fetch(url, {
                    method: method,
                    body: formData
                });

                // Handle potential 401/403 redirects by checking for response.redirected
                if (response.redirected && response.url.includes('login.html')) {
                    alert('会话已过期，请重新登录。');
                    location.href = 'login.html';
                    return;
                }

                const result = await response.json();

                if (result.success) {
                    showMessage(result.message, 'success');
                    if (bookId) {
                        // For edit operation, redirect to dashboard
                        setTimeout(() => {
                            location.href = 'dashboard.html';
                        }, 1500);
                    } else {
                        // For add operation, clear form for new entry
                        document.getElementById('bookForm').reset();
                        document.getElementById('imagePreview').style.display = 'none';
                        document.getElementById('imagePreview').src = '';
                    }
                } else {
                    showMessage(result.message);
                }
            } catch (error) {
                console.error('Error submitting form:', error);
                showMessage('系统错误，请稍后重试');
            } finally {
                hideLoading();
            }
        });
    </script>
</body>
</html> 